/**
 * @author BYK
 */
var mpdClient = function(host, port, password)
{
	this.host = host || 'localhost';
	this.port = port || 6600;
	this.response = '';
	this.queue = [];
	this.socket = new air.Socket();

	var self = this, 
	dataReader = function(event)
	{
		self.response += self.socket.readUTFBytes(self.socket.bytesAvailable);
		if (self.response.substr(0, 6) == 'OK MPD')
			self.response = self.response.substr(self.response.indexOf('\n') + 1);

		var error = self.response.substr(0, 5) == 'ACK [',
		success = self.response.substr(self.response.length - 3, 2) == 'OK'; 
		if (success || error || !self.response) 
		{
			if (success) 
			{
				var queueItem = self.queue.pop();
				queueItem.callback(mpdClient.parseResponse(self.response));
			}
			else if (error) 
				;
			self.response = '';
			self.processQueue();
		}
	};
	
	this.socket.addEventListener(air.ProgressEvent.SOCKET_DATA, dataReader);
};

mpdClient.prototype.processQueue = function()
{
	if (!this.queue.length)
		return false;
	if (!this.socket.connected) 
	{
		air.trace('Not connected, connecting now...');
		this.socket.connect(this.host, this.port);
		return;
	}
	
	this.socket.writeUTFBytes(this.queue[0].command + '\n');
	this.socket.flush();
};

mpdClient.prototype.request = function(command, callback)
{
	if (this.queue.push({command: command, callback: callback}) == 1)
		this.processQueue();
};

mpdClient.parseResponse = function(response)
{
	return response;
};
